import trim from "lodash/trim";
import isNumber from "lodash/isNumber";

/**
 * 移除字符串左右两头的空格
 * ======================================
 * @param str
 * @returns {*}
 */
export const trim = (str) => {
  return str.replace(/^\s+/, "").replace(/\s+$/, "");
};
/**
 * 判断是否为字符串类型数值
 * ======================================
 * @param {String} str - 要检测的（字符串）数据
 * @returns {boolean}
 */
export const isString = (str) => {
  return typeof str === "string";
};

/**
 * 生成 UUID 值方法
 * =============================================================
 * @param {Number} [len]
 * @param {Number} [radix]
 * @returns {string}
 */
export const uuid = (len, radix) => {
  let chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  let uuid = [];
  let i;

  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++) {
      uuid[i] = chars[0 | (Math.random() * radix)];
    }
  } else {
    let r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join("");
};

function generateUUID1() {
  var d = new Date().getTime();
  var d2 =
    (typeof performance !== "undefined" &&
      performance.now &&
      performance.now() * 1000) ||
    0;
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = Math.random() * 16;
    if (d > 0) {
      r = (d + r) % 16 | 0;
      d = Math.floor(d / 16);
    } else {
      r = (d2 + r) % 16 | 0;
      d2 = Math.floor(d2 / 16);
    }
    return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
}
//ES6语法
const generateUUID2 = () => {
  let d = new Date().getTime(),
    d2 =
      (typeof performance !== "undefined" &&
        performance.now &&
        performance.now() * 1000) ||
      0;
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    let r = Math.random() * 16;
    if (d > 0) {
      r = (d + r) % 16 | 0;
      d = Math.floor(d / 16);
    } else {
      r = (d2 + r) % 16 | 0;
      d2 = Math.floor(d2 / 16);
    }
    return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);
  });
};

function generateUUID3() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

/**
 * 字符串转对象
 * @param {String} str - 字符串
 * @param {String} separator - 分隔符
 */
function stringToObj(str, separator) {
  return Object.fromEntries(
    str.split(separator).map((pair) => pair.split("="))
  );
}
//es5语法
function stringToObjES5(str, separator) {
  return str.split(separator).forEach((pair) => {
    const [key, value] = pair.split("=");
    obj[key] = value;
  });
}

// 搜索高亮关键字
export const highlight = (name, key) => {
  const reg = new RegExp("(" + trim(key) + ")", "ig");

  if (reg.test(name)) {
    return name.replace(reg, '<strong class="highlight">$1</strong>');
  }

  return name;
};

// 过滤两位小数
export const filterPoint = (value) => {
  // 清除 "数字" 和 "." 以外的字符
  value = value.replace(/[^0-9.]/g, "");
  // 清除以 "." 开头的金额, 也可以替换为 0.
  value = value.replace(/^\./g, "");
  // 将连续多个 "." 替换为一个 "."
  value = value.replace(/\.{2,}/g, ".");
  // 只能输入两位小数
  value = value.replace(/^(\d+)\.(\d)(\d).*$/, "$1.$2$3");
  // 防止 2.2.2.2 这种多个. 的产生
  value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
  if (!value.includes(".") && value !== "") {
    // parseFloat()可解析一个字符串，并返回一个浮点数。
    value = parseFloat(value);
  }
  return value;
};

/**
 * 格式化文件大小单位
 * ====================================================
 * @param {Number} limit - 文件大小
 */
export const fileSizeConvert = (limit) => {
  let size = "";

  if (!isNumber(limit) || isNaN(limit) || limit === 0) {
    return "--";
  }

  if (limit < 0.1 * 1024) {
    // 如果小于0.1KB转化成B
    size = limit.toFixed(2) + "B";
  } else if (limit < 0.1 * 1024 * 1024) {
    // 如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + "KB";
  } else if (limit < 1024 * 1024 * 1024) {
    // 如果小于1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  } else {
    // 其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }

  let sizestr = size + "";
  let len = sizestr.indexOf(".");
  let dec = sizestr.substr(len + 1, 2);

  if (dec === "00") {
    // 当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
  }

  return sizestr;
};

// 过滤中文字符
export const filterChinese = (value) => {
  value = value.replace(/[\u4E00-\u9FA5]/g, "");
  return value;
};

/**
 * 获取扩展名
 * ======================================
 * @param str
 * @returns {string}
 */
export const getFileExtension = (str) => {
  let index = str.lastIndexOf(".");

  return str.substring(index + 1).toLowerCase();
};

/**
 * 获取字符长度
 * ======================================
 * @param val
 * @returns {number}
 */
export const getStrLength = (val) => {
  let len = 0;

  for (let i = 0; i < val.length; i++) {
    let char = val.charAt(i);

    if (char.match(/[^x00-xff]/gi) !== null) {
      len += 2;
    } else {
      len += 1;
    }
  }

  return len;
};

/**
 * 去除所有的空格
 * @param {String} str
 */
export const trimAll = (str) => {
  return str.replace(/\s+/g, "");
};

/**
 * 获取扩展名
 * ======================================
 * @param str
 * @returns {string}
 */
export const getExtension = (str) => {
  let index = str.lastIndexOf(".");

  return str.substring(index + 1).toLowerCase();
};
